package com.hsy.order.order.ui

import android.media.AudioManager
import android.media.SoundPool
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View

import com.flux.action.RxStoreChange
import com.flux.utils.LogUtil
import com.hsy.order.R
import com.hsy.order.base.action.ActionType
import com.hsy.order.base.ui.fragment.BaseFragment
import com.hsy.order.common.ui.MainActivity
import com.hsy.order.order.action.HomeActionCreator
import com.hsy.order.order.store.ListStore
import com.hsy.order.utils.CommonUtils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener

import java.util.*
import kotlin.concurrent.timerTask
import kotlinx.android.synthetic.main.layout_list_empty.*
import kotlinx.android.synthetic.main.layout_refresh_recycle.*


/**
 * 首页列表Fragment
 * Created on 2018/3/28.
 *
 * @author Yang
 */
class ListFragment : BaseFragment<ListStore>(), OnRefreshListener {

    private var failureView: View? = null
    /**
     * 事件产生器
     */
    private val creator = HomeActionCreator(dispatcher, manager)
    /**
     * 数据缓存器
     */
    override var store = ListStore(dispatcher)
    /**
     * 布局文件
     */
    override val fragmentLayout: Int
        get() = R.layout.layout_refresh_recycle

    /**
     * 问答分类
     */
    private lateinit var tab: String
    /**
     * 我的问答适配器
     */
    private val adapter = OrderAdapter(this, listOf(), ::onClick)

    private var isCreate = false
    private var init = true

    /**
     * 自动刷新定时器
     */
    private var timer = Timer()
    /**
     * 上一次刷新的ID
     */
    private var preID = "-1"
    /**
     * 声音播放器
     */
    private lateinit var soundPool: SoundPool
    /**
     * 声音播放ID
     */
    private var soundID = -1

    private val interval = CommonUtils.getReloadInterval()

    override fun initView(view: View?) {
        tab = arguments!!.getString("tab")
        isCreate = true
        store.setRxTag(tab)
        refresh.setOnRefreshListener(this)
        refresh.isEnableLoadMore = false
        recycle.layoutManager = LinearLayoutManager(recycle.context)
        recycle.adapter = adapter
        listEmptyView.setOnClickListener {
            CommonUtils.showProgressDialog(context)
            onRefresh(refresh)
        }
        soundPool = SoundPool(5, AudioManager.STREAM_RING, 0)
        soundID = soundPool.load(context, R.raw.ring, 1)
    }

    override fun initData() {
        super.initData()
        if (!init) {
            CommonUtils.showProgressDialog(context)
            onRefresh(refresh)
            init = true
            if (tab == "1") {
                timer = Timer()
                timer.schedule(timerTask { activity?.runOnUiThread { refresh.autoRefresh(0) } }, interval, interval)
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            init = isCreate
            if (isCreate) {
                CommonUtils.showProgressDialog(context)
                onRefresh(refresh)
                if (tab == "1") {
                    timer = Timer()
                    timer.schedule(timerTask { activity?.runOnUiThread { refresh.autoRefresh(0) } }, interval, interval)
                }
            }
        } else {
            timer.cancel()
        }
    }

    /**
     * 重载刷新事件
     */
    override fun onRefresh(refresh: RefreshLayout) {
        store.page = "1"
        creator.getHomeData(tab, store.page, tab)
    }

    /**
     * 界面响应统一处理
     * @param change 需要界面响应的变化
     */
    override fun onRxStoreChanged(change: RxStoreChange) {
        if (change.storeId == store.tag) when (change.type) {
            ActionType.GET_HOME_DATA + tab -> {
                CommonUtils.hideProgressDialog()
                refresh.finishRefresh()
                if (change.success) {
                    if (failureView != null) {
                        homeParent.removeView(failureView)
                        failureView = null
                    }
                    handleList()
                } else {
                    failureView = context?.let { CommonUtils.showNetworkFailure(it, homeParent, View.OnClickListener { onFragmentRefresh() }) }
                }
            }
            else -> if (change.success){
                onRefresh(refresh)
                showToast("操作成功")
            }
        }
    }

    private fun handleList() {
        adapter.items = store.homeData
        adapter.notifyDataSetChanged()
        listEmptyView.visibility = if (adapter.items.isNotEmpty()) View.GONE else View.VISIBLE
        val id = if (adapter.items.isEmpty()) "-1" else adapter.items[0].id
        if (preID != id && id != "-1" && tab == "1" && soundID != -1) soundPool.play(soundID, 1f, 1f, 0, 0, 1f)
        preID = id
        if (tab == "1" && adapter.items.isNotEmpty() && CommonUtils.getAutoAccept()) {
            (activity as MainActivity).onPrint(store.homeData[0])
            creator.acceptOrder(store.homeData[0].id)
        }
    }

    fun onClick(type: Int, position: Int) {
        when (type) {
            0 -> creator.refuseOrder(store.homeData[position].id)
            1 -> (activity as MainActivity).onPrint(store.homeData[position])
            2 -> creator.acceptOrder(store.homeData[position].id)
            3 -> creator.dispatchOrder(store.homeData[position].id)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LogUtil.i("onDestroyView")
        isCreate = false
        if (tab == "1") {
            timer.cancel()
        }
        soundPool.release()
    }

    override fun getRxTag() = super.getRxTag() + tab

    companion object {
        /**
         * 获取一个Fragment实例
         */
        fun getInstance(tab: String): ListFragment {
            val fragment = ListFragment()
            val argument = Bundle()
            argument.putString("tab", tab)
            fragment.arguments = argument
            return fragment
        }
    }
}